
#include "core/handle.h"
#include "core/core_error.h"
#include "config.h"

Handle Handle::kInvalid(-1);

Handle Handle::New(uint32_t serial_number) {
  std::string svr_id_str = Config::Get("server.svr_id");
  uint32_t svr_id = boost::lexical_cast<uint32_t>(svr_id_str);
  return Handle(svr_id, serial_number);
}

Handle::Handle(uint32_t value) {
  Init((value & kSvrIdMask) >> kShift, value & kValMask);
}

Handle::Handle(uint32_t svr_id, uint32_t serial_number) {
  Init(svr_id, serial_number);
}

void Handle::Init(uint32_t svr_id, uint32_t serial_number) {
  if (serial_number > Handle::MaxSN()) {
    THROW(core_error::handle_serial_number_overflow); 
  }

  if (svr_id > Handle::MaxSvrId()) {
    THROW(core_error::svr_id_overflow);
  }

  value_ = serial_number | (svr_id << kShift);
}

